package com.imc.platform.base.banner.controller;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.imc.core.utils.ClearTempImg;
import com.imc.core.utils.MenuUtils;
import com.imc.core.utils.MysqlUtil;
import com.imc.platform.base.banner.pojo.Banner;
import com.imc.platform.base.banner.pojo.BannerItem;
import com.imc.platform.base.banner.service.IBannerService;
import com.twp.common.tuple.ResultDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.POST;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;

/*
 *  类描述：banner
 *  开发者：sjc
 *  创建时间：2018-8-3 14:29:47
 */
@Slf4j
@Controller
public class BannerController {

    public static final String imgUrl = "/images/banner/";
    @Autowired
    IBannerService iBannerService;
    @Autowired
    MysqlUtil mysqlUtil;

    @Autowired
    MenuUtils menuUtils;
    @Autowired
    ClearTempImg clearTempImg;
    /*
     *  sjc 2018-8-17 10:01:50
     *  方法描述：banner页面跳转
     */
    @RequestMapping("/index/bannerManage")
    public String bannerManage(String menuId, Model model, HttpServletRequest request) {
        model.addAttribute("menu", menuUtils.getMenuByRoleId(request, menuId));
        return "base/banner/bannerManage";
    }

    /*
     *  sjc 2018-8-17 15:22:33
     *  方法描述： 查询banner列表
     */
    @RequestMapping("/query/queryBanner")
    @ResponseBody
    public ResultDTO queryBanner(
            Pageable pageable
    ) {
        PageInfo <Banner> bannerList = iBannerService.queryBanner(pageable.getPageNumber(), pageable.getPageSize());
        for(Banner c : bannerList.getList()){
            c.setPageNumber(pageable.getPageNumber());
            c.setPageSize(pageable.getPageSize());
        }
        JSONObject map = new JSONObject();
        map.put("total", bannerList.getTotal());
        map.put("rows", bannerList.getList());
        ResultDTO obj = ResultDTO.builder().data(map).build();
        return obj;
    }

    /**
     * 方法描述:
     * SJC 2018-9-5 20:20:13
     */
    @RequestMapping(value = "/banner/updateBannerState", method = RequestMethod.POST)
    @ResponseBody
    public ResultDTO updateBannerState(
            @RequestParam String id, @RequestParam String state
    ) throws Exception {
        int count = iBannerService.updateBannerState(id, state);
        JSONObject map = new JSONObject();
        map.put("count", count);
        ResultDTO obj = ResultDTO.builder().data(map).build();
        return obj;
    }

    /**
     * 方法描述:跳转到新增页面
     * SJC 2018-8-19 19:04:51
     */
    @GetMapping("/banner/openAddBanner")
    public String toaddBanner() throws Exception {
        return "base/banner/addBanner";
    }

    /**
     * 方法描述:新增banner主表
     * SJC 2018-8-28 20:24:47
     */
    @RequestMapping(value = "/banner/addBanner", method = RequestMethod.POST)
    @ResponseBody
    public ResultDTO addBanner(@RequestParam String bannerName, @RequestParam String bannerType) throws Exception {
        Banner bn = new Banner();
        String bnId = mysqlUtil.getMaxId("t_banner");
        bn.setId(bnId);
        bn.setBannerName(bannerName);
        bn.setState(1);
        bn.setBannerType(bannerType);
        String dateStr = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        bn.setCreateTime(dateStr);
        int count = iBannerService.addBanner(bn);
        JSONObject map = new JSONObject();
        map.put("bnId", bnId);
        ResultDTO obj = ResultDTO.builder().data(map).build();
        return obj;
    }

    /**
     * 方法描述:修改banner名称
     * SJC 2018-8-28 20:24:47
     */
    @RequestMapping("/banner/updateBannerName")
    @ResponseBody
    public ResultDTO updateBannerName(String bnId, String bannerName, String bannerType) throws Exception {
        Banner bn = new Banner();
        bn.setId(bnId);
        bn.setBannerName(bannerName);
        bn.setBannerType(bannerType);
        int id = iBannerService.updateBanner(bn);
        JSONObject map = new JSONObject();
        map.put("bnId", id);
        ResultDTO obj = ResultDTO.builder().data(map).build();
        return obj;
    }

    //绝对路径
    public String path(HttpServletRequest request) {
        //开发用：
//        String indeStr = "http://" + request.getServerName() // 服务器地址
//                + ":" + request.getServerPort() // 端口号
//                + request.getContextPath(); // 项目名称
//        //现网：
//        /*String indeStr = "https://" + request.getServerName() // 服务器地址
//                + request.getContextPath(); // 项目名称*/
        return accessPath + imgUrl;
    }

    @Value("${img.location}")
    String location;

    @Value("${img.accessPath}")
    String accessPath;

    //相对路径
    public String savePath(HttpServletRequest request) {
        //String savePath = request.getSession().getServletContext().getRealPath(imgUrl);
        return location + imgUrl;
    }

    /**
     * 方法描述:新增bannerItem
     * SJC 2018-8-28 20:24:47
     */
    @RequestMapping("/banner/addBannerItem")
    @ResponseBody
    public ResultDTO addBannerItem(@RequestParam("file") MultipartFile file, String bnId, HttpServletRequest request) throws Exception {
        JSONObject map = new JSONObject();
        //图片模块上传多图片时候，只新增附件表。
        if (null != bnId && !"".equals(bnId)) {
            String realPath = path(request);
            String savePath = savePath(request);
            String fileName = upImg(savePath, file);
            if (null != fileName && !"".equals(fileName)) {
                map.put("reCode", "4001");
                BannerItem bi = new BannerItem();
                String biId = mysqlUtil.getMaxId("t_banner_item");
                bi.setId(biId);
                bi.setParentId(bnId);
                bi.setImgName(fileName);
                bi.setImgUrl(realPath + fileName);
                int count = iBannerService.addBannerItem(bi);
                if (count == 0) {
                    //附件新增失败
                    map.put("reCode", "4004");
                } else {
                    map.put("reCode", "4001");
                    map.put("biId", biId);
                    map.put("imgName", fileName);
                    map.put("imgUrl", realPath + fileName);
                }
            } else {
                //图片上传失败
                map.put("reCode", "4002");
            }

        }
        ResultDTO obj = ResultDTO.builder().data(map).build();
        return obj;
    }

    /**
     * 方法描述:补充banner图片内容
     * SJC 2018-8-28 20:24:47
     */
    @RequestMapping("/banner/updateBannerItem")
    @ResponseBody
    public ResultDTO updateBannerItem(String bannerItemId, String bnImgDes, String targetUrl) throws Exception {
        BannerItem bi = new BannerItem();
        bi.setId(bannerItemId);
        bi.setDescription(bnImgDes);
        bi.setTargetUrl(targetUrl);
        int count = iBannerService.updateBannerItem(bi);
        JSONObject map = new JSONObject();
        if (count == 0) {
            //没有受影响的行数
            map.put("reObj", "4002");
        } else {
            map.put("reObj", "4001");
        }
        map.put("count", count);
        ResultDTO obj = ResultDTO.builder().data(map).build();
        return obj;
    }

    /**
     * 方法描述:删除banner图片
     * SJC 2018-8-28 20:24:47
     */
    @RequestMapping("/banner/delBannerItem")
    @ResponseBody
    public ResultDTO delBannerItem(String parentId, String imgName) throws Exception {
        BannerItem bi = new BannerItem();
        bi.setParentId(parentId);
        bi.setImgName(imgName);
        clearTempImg.clearImgs(imgName);
        int count = iBannerService.delBannerItem(bi);
        JSONObject map = new JSONObject();
        if (count == 0) {
            //没有受影响的行数
            map.put("reObj", "4002");
        } else {
            map.put("reObj", "4001");
        }
        map.put("count", count);
        ResultDTO obj = ResultDTO.builder().data(map).build();
        return obj;
    }

    /**
     * 方法描述:banner图片排序
     * SJC 2018-8-28 20:24:47
     */
    @RequestMapping("/banner/updateBannerItemSn")
    @ResponseBody
    public ResultDTO updateBannerItemSn(String itemName) throws Exception {
        List <String> nameList = Arrays.asList(itemName.split(","));

        int count = iBannerService.updateBannerItemSn(nameList);
        JSONObject map = new JSONObject();
        if (count == 0) {
            //没有受影响的行数
            map.put("reObj", "4002");
        } else {
            map.put("reObj", "4001");
        }
        map.put("count", count);
        ResultDTO obj = ResultDTO.builder().data(map).build();
        return obj;
    }

    /**
     * 方法描述:图片上传 返回图片路径
     * SJC 2018-8-26 16:03:21
     */
    private String upImg(String savePath, MultipartFile file) {

        String relFn = null;
        try {
            if (null != file) {
                String filename = URLEncoder.encode(file.getOriginalFilename(), "utf-8");
                File filepath = new File(savePath, filename);
                //判断路径是否存在，如果不存在就创建一个
                if (!filepath.getParentFile().exists()) {
                    filepath.getParentFile().mkdirs();
                }

                InputStream inputStream = file.getInputStream();
                FileOutputStream fileOutputStream = null;
                String fnName = makeFileName(filename);
                relFn = fnName;
                byte[] data = new byte[1024];
                int len = 0;
                fileOutputStream = new FileOutputStream(savePath + fnName);
                while ((len = inputStream.read(data)) != -1) {
                    fileOutputStream.write(data, 0, len);
                }
                fileOutputStream.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return relFn;
    }

    private static String makeFileName(String filename) { //2.jpg
        //为防止文件覆盖的现象发生，要为上传文件产生一个唯一的文件名
        // String extname = filename.substring(filename.lastIndexOf("."),filename.length());
        return UUID.randomUUID().toString() + "_" + filename;
    }

    /**
     * 方法描述:打开详情页
     * SJC 2018-8-30 20:15:29
     */
    @GetMapping("/banner/showBannerInfo")
    public String showBannerInfo(@RequestParam String bnId, Model model) throws Exception {
        List <BannerItem> itemList = iBannerService.getBannerItemInfo(bnId);
        String bannerName = iBannerService.getBannerName(bnId);
        model.addAttribute("itemList", itemList);
        model.addAttribute("bannerName", bannerName);
        return "base/banner/bannerInfo";
    }

    /**
     * 方法描述:打开详情页
     * SJC 2018-8-30 20:15:29
     */
    @GetMapping("/banner/toEditBanner")
    public String toEditBanner(@RequestParam String bnId, Model model) throws Exception {
        List <BannerItem> itemList = iBannerService.getBannerItemInfo(bnId);
        String bannerName = iBannerService.getBannerName(bnId);
        model.addAttribute("bnId", bnId);
        model.addAttribute("itemList", itemList);
        model.addAttribute("bannerName", bannerName);
        return "base/banner/updateBanner";
    }

    /**
     * 方法描述:根据id删除Banner
     * SJC 2018-9-4 21:52:41
     */
    @RequestMapping(value = "/banner/delBanner", method = RequestMethod.POST)
    @ResponseBody
    public ResultDTO delRole(@RequestParam String id) {
        return ResultDTO.builder()
                .data(iBannerService.delBanner(id))
                .build();
    }

}